package com.aisile.crowd_funding.system.controller;

import com.aisile.crowd_funding.common.utils.PageUtils;
import com.aisile.crowd_funding.common.utils.Query;
import com.aisile.crowd_funding.common.utils.R;
import com.aisile.crowd_funding.system.pojo.SysRole;
import com.aisile.crowd_funding.system.pojo.SysUser;
import com.aisile.crowd_funding.system.service.RoleService;
import com.aisile.crowd_funding.system.service.UserService;
import com.github.pagehelper.PageHelper;
import excel.ExcelUtils;
import excel.POIConstant;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @标题 UserController
 * @作者 Mr.chen
 * @创建日期 2018/12/14 10:40
 * @版本号 1.0
 **/
@Controller
@RequestMapping("sys/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Value("${web-upload-path}")
    private String imgRealPath;
    @Autowired
    private ResourceLoader resourceLoader;


    @RequestMapping
    public String index(){
        return "system/user/user";
    }

    /**
     * 用户分页方法
     * @param params
     * @return
     */
    @RequestMapping("list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String,String> params){
        return userService.selectByPage(params);
    }

    @RequestMapping("add")
    public String add(Model model){
        List<SysRole> sysRoles = roleService.selectByExample(null);
        model.addAttribute("roleList",sysRoles);
        return "system/user/add";
    }

    /**
     * 保存
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public R save(SysUser sysUser){
        int insert = userService.insert(sysUser);
        if(insert>0){
            return R.ok();
        }
        return R.error();
    }


    @RequestMapping("hasUser")
    @ResponseBody
    public boolean hasUser(String username){
        SysUser sysUser = userService.findByUserName(username);
        if(sysUser!=null){
            //有用户
            return false;
        }
        return true;
    }

    /**
     * 上传文件
     * @param myFile
     * @return
     * @throws Exception
     */
    @RequestMapping("photo")
    @ResponseBody  //   .jpg   png
    public R photo(@RequestParam(value = "myFile") MultipartFile myFile,String name) throws Exception{
        String oldFileName = myFile.getOriginalFilename();//获取原文件名
        //重命名
        String newName = UUID.randomUUID().toString();
        String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = newName+suffix;//存入数据库  imgPath :214324324.png
        //转存文件
        myFile.transferTo(new File(imgRealPath + newFileName));
        return R.ok(newFileName);
    }
    /**
     * 用户导出
     * @param response
     * @throws Exception
     */
    @RequestMapping("export")
    public void export(HttpServletResponse response) throws Exception{
        // 1.准备好数据
        List<SysUser> sysUsers = userService.selectByExample(null);
        //2.起标题
        String tilte = "会议列表";
        //3.起表头
        String[] headers = {"用户ID","用户名","昵称","邮箱","联系方式"};
        //4.定义字段
        Object[][] fields = {
                {"userId", POIConstant.AUTO},
                {"username", POIConstant.AUTO},
                {"name", POIConstant.AUTO},
                {"email", POIConstant.AUTO},
                {"mobile", POIConstant.AUTO}
        };
        //5.定义规则
        ExcelUtils.ExportRules rules = new ExcelUtils.ExportRules(false,fields,tilte,headers,null);
        //6.创建excel
        Workbook workbook = ExcelUtils.createWorkbook(sysUsers, rules);

        //7 设置相应参数
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("会议列表.xls").getBytes(), "iso-8859-1"));

        //8 输出到前台
        workbook.write(response.getOutputStream());
    }

    /**
     * 用于图片回显
     * @param imgName
     * @return
     */
    @RequestMapping("image/{imgName}")
    public ResponseEntity getImage(@PathVariable String imgName){
        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + imgRealPath + imgName));
        }catch (Exception e){
            return ResponseEntity.notFound().build();
        }
    }
}
